package com.asiainfo.codeclean;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Segment {
	static final Pattern p = Pattern.compile("(/\\*{1,2}[\\s\\S]*?\\*/)|(//[\\s\\S]*?(?=\\n))");
	private int start, end;
	private String content;
	private boolean isComment;

	public Segment(String code, int start, int end, boolean isComment) {
		this.content = code.substring(start, end);
		this.start = start;
		this.end = end;
		this.isComment = isComment;
	}

	public String getContent() {
		return content;
	}

	public boolean isComment() {
		return isComment;
	}

	@Override
	public String toString() {
		// return "Segment [start=" + start + ", end=" + end + ", content=" +
		// content + ", isComment=" + isComment + "]";
		return "Segment [start=" + start + ", end=" + end + ", isComment=" + isComment + "]";
	}

	public static List<Segment> splitSegment(String code) {
		List<Segment> commentSegs = new ArrayList<Segment>();
		Matcher m = p.matcher(code);
		while (m.find()) {
			int end = m.end();
			int start = m.start();
			commentSegs.add(new Segment(code, start, end, true));
		}
		int start = 0;
		Segment commentSeg = null;
		List<Segment> segs = new ArrayList<Segment>();
		Iterator<Segment> it = commentSegs.iterator();
		while (it.hasNext()) {
			commentSeg = it.next();
			if (commentSeg.start > start) {
				segs.add(new Segment(code, start, commentSeg.start, false));
				if (it.hasNext()) {
					start = commentSeg.end;
				}
			}
		}
		if (commentSeg != null && commentSeg.end < code.length()) {
			segs.add(new Segment(code, commentSeg.end, code.length(), false));
		}
		segs.addAll(commentSegs);
		Collections.sort(segs, new Comparator<Segment>() {
			public int compare(Segment o1, Segment o2) {
				return o1.start - o2.start;
			}
		});
		return segs;
	}

	public static String toCode(List<Segment> segments) {
		StringBuilder newCode = new StringBuilder();
		for (Segment segment : segments) {
			newCode.append(segment.getContent());
		}
		return newCode.toString();
	}

	public static String toSimpleCode(List<Segment> segments) {
		StringBuilder newCode = new StringBuilder();
		for (Segment segment : segments) {
			if (segment.isComment)
				continue;
			newCode.append(segment.getContent());
		}
		return newCode.toString();
	}

	public int getStart() {
		return start;
	}

	public void setStart(int start) {
		this.start = start;
	}

	public int getEnd() {
		return end;
	}

	public void setEnd(int end) {
		this.end = end;
	}

	public void setContent(String content) {
		this.content = content;
	}

	public void setComment(boolean isComment) {
		this.isComment = isComment;
	}

}
